const App = getApp();
const func = require('../../utils/func');

Page({
    /**
     * 页面的初始数据
     */
    data: {
        // 订单参数
        page: 1,
        total: 0,
        perPage: 0,
        lastPage: 1,
        isLoading: true,
        loadOrder: false,
        nullOrder: false,
        shopOrder: {},
        // 商品异常参数
        abnormal: false,
        abnormalTitle: '',
        abnormalGoods: {},
        abnormalOrderID: 0,
        abnormalGoodsID: {},
        showChoosePopup:false,
        // 小程序消息模板信息
        tmplData: [],
        // 小程序消息模板ids
        tmplIds: [],
        Login:false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let _this = this;
        // 设置数据类型
        _this.setData({
            dataType: options.type || 'all'
        });
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let _this = this;
        if (App.checkIsLogin() == true) {
            // 获取订单列表
            _this.getOrderList();
            _this.setData({
                isLogin: App.checkIsLogin(),
            })
        } else {
            _this.setData({
                Login: !App.checkIsLogin(),
                isLoading: false,
            })
        }
    },
    
    // 下拉刷新
    onPullDownRefresh() {
        let _this = this;
        _this.data.page = 1;
        _this.data.lastPage = 1;
        // 获取订单列表
        _this.getOrderList();
        wx.stopPullDownRefresh();
    },

    // 上拉加载
    onReachBottom() {
        let _this = this;
        if (_this.data.perPage >= _this.data.total) return false;
        _this.setData({loadOrder: true});
        if (_this.data.page >= _this.data.lastPage) {
            _this.setData({nullOrder: true, loadOrder: false, isLoading: false});
            return false;
        }
        _this.getOrderList(true, ++_this.data.page);
    },
    
    // 展示弹窗
    showLogin() {
        App.doLogin()
    },
	    /**
     * 授权登录
     */
    getUserInfo(e) {
        let _this = this;
        App.getUserInfo(e, () => {
        // 跳转回原页面
            wx.reLaunch({
              url: '/pages/order/index',
            })
        });
    },
    changePage() {
        wx.navigateBack({
            delta:1
        })
    },
    // 获取订单列表
    getOrderList(isPage, page) {
        let _this = this;
        let postData = {
            page: page || 1,
            dataType: _this.data.dataType
        };
        App._requestApi(_this, App.globalData.config.shopOrderListsUrl, postData, function (res) {
            // 显示页面
            _this.setData({nullOrder: false, loadOrder: false, isLoading: false, config: res.data.config});
            // 订单数据
            let resOrder = res.data.data;
            if (isPage == true) {
                if (resOrder.length == 0) {
                    _this.setData({nullOrder: true});
                } else {
                    let shopOrder = _this.data.shopOrder;
                    _this.setData({shopOrder: shopOrder.concat(resOrder)});
                }
            } else {
                _this.setData({
                    shopOrder: resOrder,
                    total: res.data.total,
                    perPage: res.data.per_page,
                    lastPage: res.data.last_page,
                });
            }
        });
    },

    // 切换订单状态查询
    swichOrderStatus(e) {
        let _this = this;
        _this.setData({
            shopOrder: {},
            isLoading: true,
            dataType: e.currentTarget.dataset.current
        });
        // 获取订单列表
        _this.data.page = 1;
        _this.data.lastPage = 1;
        _this.getOrderList();
    },

    // 付款方式选择弹窗
    showChoose(e){
        let _this = this;
        _this.setData({
            showChoosePopup: !_this.data.showChoosePopup
        })
    },

    // 订单立即付款
    orderSubmitPay(e) {
        let _this = this;
        let payOrderID = e.currentTarget.dataset.id;
        let payOrderCode = e.currentTarget.dataset.code;
        if (true === _this._orderValidity(payOrderID)) {
            // 发起付款请求
            _this._orderDirectPay(payOrderID, payOrderCode);
        }
    },

    // 发起付款请求
    _orderDirectPay: function(payOrderID, payOrderCode) {
        let _this = this;
        let postData = {
            action: 'directPay',
            order_id: payOrderID,
            order_code: payOrderCode
        };
        App._requestPost(_this, App.globalData.config.shopOrderPayUrl, postData, function (res) {
			_this.data.tmplData = res.data.tmplData;
			for (let key in _this.data.tmplData) {
				_this.data.tmplIds.push(_this.data.tmplData[key]['template_id']);
			}
            if (res.data.weChatPay.return_code == 'FAIL') {
                App.showError(res.data.weChatPay.return_msg);
                return false;
            }
            App.wxPayment({
                order_id: payOrderID,
                payment: res.data.weChatPay,
                success: res1 => {
                    // 支付后续处理
                    _this._orderPayHandle(payOrderID, payOrderCode);
                },
                fail: res1 => {
                    if (!res.msg.error) App.showError(res.msg.error);
                },
            });
        },
        function (res) {
            App.showError(res.msg);
        });
    },

    // 支付后续处理
    _orderPayHandle: function(payOrderID, payOrderCode) {
        if (payOrderID && payOrderCode) {
            let _this = this;
            let postData = {
                order_id: payOrderID,
                order_code: payOrderCode
            };
            App._requestPost(_this, App.globalData.config.shopOrderPayHandleUrl, postData, function (res) {
				if (_this.data.tmplIds.length > 0) {
					wx.requestSubscribeMessage({
						tmplIds: _this.data.tmplIds,
						success (res1) {
							let is_send = false;
							for (let key in res1) {
								if (_this.data.tmplData[key] && 5 == _this.data.tmplData[key]['send_scene'] && 'accept' == res1[key]) {
									if (is_send === false) {
										is_send = true;
									}
								}
							}
							if (is_send === true) {
								App._requestApi(_this, App.globalData.config.apiSendWeixniNoticeUrl, {
									result_id: payOrderID,
									send_scene: 5,
								}, function(res2) {
									wx.navigateTo({url: res.url});
								});
							} else {
								wx.navigateTo({url: res.url});
							}
						}
					})
				} else {
					App.showSuccess(res.msg, function() {
						wx.navigateTo({url: res.url});
					});
				}
            },
            function (res) {
                App.showError(res.msg);
            });
        }
    },

    // 订单取消
    orderCancel(e) {
        let _this = this;
        let orderID = e.currentTarget.dataset.id;
        if (true === _this._orderValidity(orderID)) {
            wx.showModal({
                title: "友情提示",
                content: "确认要取消该订单吗？",
                success(o) {
                    if (o.confirm) {
                        let postData = {
                            action: 'cancel',
                            order_id: orderID
                        };
                        App._requestPost(_this, App.globalData.config.shopOrderActionUrl, postData, function (res) {
                           wx.showToast({
                             title:res.msg,
                           })
                           _this.getOrderList();
                           
                        });
                    }
                }
            });
        }
    },

    // 订单提醒发货
    orderRemindSend(e) {
        let _this = this;
        let orderID = e.currentTarget.dataset.id;
        if (true === _this._orderValidity(orderID)) {
            wx.showModal({
                title: "友情提示",
                content: "需要提醒管理员发货？",
                success(o) {
                    if (o.confirm) {
                        let postData = {
                            action: 'remind',
                            order_id: orderID
                        };
                        App._requestPost(_this, App.globalData.config.shopOrderActionUrl, postData, function (res) {
                            wx.showToast({
                              title: res.msg,
                            })
                        });
                    }
                }
            });
        }
    },

    // 订单确认收货
    orderConfirmReceipt(e) {
        let _this = this;
        let orderID = e.currentTarget.dataset.id;
        if (true === _this._orderValidity(orderID)) {
            wx.showModal({
                title: "友情提示",
                content: "确认收到订单商品？",
                success(o) {
                    if (o.confirm) {
                        let postData = {
                            action: 'confirm',
                            order_id: orderID
                        };
                        App._requestPost(_this, App.globalData.config.shopOrderActionUrl, postData, function (res) {
                            _this.getOrderList();
                            wx.showToast({
                              title: res.msg,
                            })
                        });
                    }
                }
            });
        }
    },

    // 订单再次购买
    orderAgainBuy(e) {
        let _this = this;
        let orderID = e.currentTarget.dataset.id;
        if (true === _this._orderValidity(orderID)) {
            let postData = {
                action: 'againBuy',
                order_id: orderID,
                goods_id: 0,
            };
            App._requestPost(_this, App.globalData.config.shopOrderActionUrl, postData, function (res) {
                if (1 === parseInt(res.data.abnormal)) {
                    App.showError(res.msg);
                } else if (2 === parseInt(res.data.abnormal)) {
                    _this.setData({
                        abnormalTitle: res.msg,
                        abnormalOrderID: orderID,
                        abnormalGoods: res.data['abnormalGoods'],
                        abnormalGoodsID: res.data['abnormalGoodsID'],
                    });
                    _this._abnormalTips();
                } else {
                    App.showSuccess(res.msg, function() {
                        wx.switchTab({url: '/pages/flow/index'});
                    });
                }
            });
        }
    },

    // 订单删除
    orderDelete(e) {
        let _this = this;
        let orderID = e.currentTarget.dataset.id;
        if (true === _this._orderValidity(orderID)) {
            wx.showModal({
                title: "友情提示",
                content: "确认要删除该订单吗？",
                success(o) {
                    if (o.confirm) {
                        let postData = {
                            action: 'deleteFind',
                            order_id: orderID
                        };
                        App._requestPost(_this, App.globalData.config.shopOrderActionUrl, postData, function (res) {
                            wx.showToast({ title:res.msg });
                           _this.getOrderList();
                        });
                    }
                }
            });
        }
    },

    // 提示弹窗展示隐藏
    _abnormalTips() {
        let _this = this;
        _this.setData({
            abnormal: !_this.data.abnormal
        });
    },

    // 订单再次购买(剔除异常商品加入购物车)
    orderAddCart() {
        let _this = this;
        let orderID = _this.data.abnormalOrderID;
        let abnormalGoodsID = _this.data.abnormalGoodsID;
        if (true === _this._orderValidity(orderID)) {
            let postData = {
                action: 'againBuy',
                order_id: orderID,
                goods_id: JSON.stringify(abnormalGoodsID),
            };
            App._requestPost(_this, App.globalData.config.shopOrderActionUrl, postData, function (res) {
                App.showSuccess(res.msg, function() {
                    wx.switchTab({url: '/pages/flow/index'});
                });
            });
        }
    },

    // 订单商品售后操作
    // orderService(e) {
    //     let _this = this;
    //     let orderID = e.currentTarget.dataset.order_id;
    //     let detailsID = e.currentTarget.dataset.details_id;
    //     let productID = e.currentTarget.dataset.product_id;
    //     if (true === _this._orderValidity(orderID)) {
    //         let postData = {
    //             use: 'service',
    //             order_id: orderID,
    //             action: 'goodsDetect',
    //             details_id: detailsID,
    //             product_id: productID,
    //         };
    //         App._requestApi(_this, App.globalData.config.shopOrderServiceActionUrl, postData, function (res) {
    //             let jumpUrl;
    //             if (parseInt(res.data.apply_service) === 1 && parseInt(res.data.service_id) !== 0) {
    //                 jumpUrl = './service/detail?service_id=' + res.data.service_id;
    //             } else {
    //                 jumpUrl = './service/apply?order_id=' + orderID + '&details_id=' + detailsID + '&product_id=' + productID
    //             }
    //             wx.navigateTo({url: jumpUrl});
    //         });
    //     }
    // },

    // 订单ID效验
    _orderValidity: function(orderID) {
        if (parseInt(orderID) > 0) {
            return true;
        } else {
            App.showError('请选择操作订单');
            return false;
        }
    },

    // 跳转添加图片界面
    addEvaluate() {
        wx.navigateTo({
            url: '/pages/comment/addcomment',
        })
    },

    // 跳转到订单详情
    jumpToView(e) {
        func.jumpToUrl(e)
    },

});